/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.easemob.chat.EMGroup;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.activity.GroupDetailsActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.ui.GroupBean;

import java.util.List;
import java.util.Map;

public class GroupFragmentAdapter extends ArrayAdapter<GroupBean> {

//    public static final Integer VIEW_TYPE_SEARCH=0;
    public static final Integer VIEW_TYPE_MY_FRIENDS=0;
    public static final Integer VIEW_TYPE_PUBLIC_GROUP=1;
    public static final Integer VIEW_TYPE_NOTICE=2; //申请与通知
    public static final Integer VIEW_TYPE_SPLIT_GROUP=3;  //功能和群组的分割线
    public static final Integer VIEW_TYPE_MY_GROUP=4;
	private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private Context context;
	public GroupFragmentAdapter(Context context, int res, List<GroupBean> groups, ImageLoader imageLoader) {
		super(context, res, groups);
        this.context=context;
		this.inflater = LayoutInflater.from(context);
        this.imageLoader=imageLoader;
	}
	
	@Override
	public int getViewTypeCount() {
		return 5;
	}
	
	@Override
	public int getItemViewType(int position) {
//	    if(position == VIEW_TYPE_SEARCH){
//	        return VIEW_TYPE_SEARCH;
//	    }else
        if(position == VIEW_TYPE_MY_FRIENDS){
	        return VIEW_TYPE_MY_FRIENDS;
	    }else if(position ==VIEW_TYPE_PUBLIC_GROUP){
            return VIEW_TYPE_PUBLIC_GROUP;
        }else if(position ==VIEW_TYPE_NOTICE){
            return VIEW_TYPE_NOTICE;
        }else if(position ==VIEW_TYPE_SPLIT_GROUP){
            return VIEW_TYPE_SPLIT_GROUP;
        }else{
	        return VIEW_TYPE_MY_GROUP;
	    }
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
//	    if(getItemViewType(position) == VIEW_TYPE_SEARCH){
//	        if (convertView == null) {
//                convertView = inflater.inflate(R.layout.search_bar_with_padding, null);
//            }
//    	    final EditText query = (EditText) convertView.findViewById(R.id.query);
//            final ImageButton clearSearch = (ImageButton) convertView.findViewById(R.id.search_clear);
//            query.addTextChangedListener(new TextWatcher() {
//                public void onTextChanged(CharSequence s, int start, int before, int count) {
//                    getFilter().filter(s);
//                    if (s.length() > 0) {
//                        clearSearch.setVisibility(View.VISIBLE);
//                    } else {
//                        clearSearch.setVisibility(View.INVISIBLE);
//                    }
//                }
//
//                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                }
//
//                public void afterTextChanged(Editable s) {
//                }
//            });
//            clearSearch.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    query.getText().clear();
//                }
//            });
//	    }else
        try {

            if (getItemViewType(position) == VIEW_TYPE_MY_FRIENDS) {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.row_add_group, null);
                }
                ((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.myfriends_icon);
                ((TextView) convertView.findViewById(R.id.name)).setText("我的邻居");
                TextView unReadMsg = (TextView) convertView.findViewById(R.id.unread_msg_number);
                new UpateUnreadCount(unReadMsg).execute(0);
                convertView.setTag(VIEW_TYPE_MY_FRIENDS);
            } else if (getItemViewType(position) == VIEW_TYPE_PUBLIC_GROUP) {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.row_add_group, null);
                }
                ((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.group_pub);
                ((TextView) convertView.findViewById(R.id.name)).setText("小区圈子");
                convertView.setTag(VIEW_TYPE_PUBLIC_GROUP);
            } else if (getItemViewType(position) == VIEW_TYPE_NOTICE) {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.row_add_group, null);
                }
                ((ImageView) convertView.findViewById(R.id.avatar)).setImageResource(R.drawable.mine_yaoqing_icon);
                ((TextView) convertView.findViewById(R.id.name)).setText("申请和通知");
                //获取未读通知的数量
                Map<String, User> user = AppContext.getInstance().getContactList();
                //添加消息数量
                TextView unReadMsg = (TextView) convertView.findViewById(R.id.unread_msg_number);
                        int unRead = getUnReadMsg();
                                if (unRead > 0) {
                                    unReadMsg.setVisibility(View.VISIBLE);
                                    unReadMsg.setText(unRead + "");
                                } else {
                                    unReadMsg.setVisibility(View.INVISIBLE);
                                }
                convertView.setTag(VIEW_TYPE_NOTICE);
            } else if (getItemViewType(position) == VIEW_TYPE_SPLIT_GROUP) {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.row_split_group, null);
                }
                convertView.setTag(VIEW_TYPE_SPLIT_GROUP);
            } else {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.row_group, null);
                }
                GroupBean groupBean=getItem(position - 4);
                EMGroup emGroup = groupBean.getEmGroup();
                ((TextView) convertView.findViewById(R.id.name)).setText(emGroup.getGroupName());
                //添加消息数量
                TextView unReadMsg = (TextView) convertView.findViewById(R.id.unread_msg_number);
                TextView descTextView = (TextView) convertView.findViewById(R.id.desc);
                descTextView.setText(emGroup.getDescription());
//                EMConversation conversation = EMChatManager.getInstance().getConversation(emGroup.getGroupId());
//                int unRead = conversation.getUnreadMsgCount();
                int unRead = groupBean.getUnRead();
                if (unReadMsg != null) {
                    if (unRead > 0) {
                        unReadMsg.setVisibility(View.VISIBLE);
                        unReadMsg.setText(unRead + "");
                    } else {
                        unReadMsg.setVisibility(View.INVISIBLE);
                    }
                }
                ImageView groupAvatar=(ImageView) convertView.findViewById(R.id.avatar);
                imageLoader.displayImage(URLs.MIHOME_GROUP_AVATAR + emGroup.getGroupId() + ".jpg?" + System.currentTimeMillis(),groupAvatar,options);
                setAvatarOnclickLinster(groupAvatar,emGroup);
                convertView.setTag(emGroup);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
		return convertView;
	}

	@Override
	public int getCount() {
		return super.getCount() + 4;
	}

    class UpateUnreadCount extends AsyncTask<Integer, Integer, Integer> {
        private TextView textView;
        public UpateUnreadCount(TextView textView){
            this.textView=textView;
        }
        @Override
        protected Integer doInBackground(Integer... integers) {
            return AppContext.getInstance().getUnReadCountFromFriends();
        }
        @Override
        protected void onPostExecute(Integer unRead) {
            if(this.textView!=null){
                if(unRead>0){
                    this.textView.setVisibility(View.VISIBLE);
                    this.textView.setText(unRead+"");
                }else{
                    this.textView.setVisibility(View.INVISIBLE);
                }
            }
            super.onPostExecute(unRead);
        }
    }
    /**
     *
     * 给头像设置点击事件，点击头像进入群资料
     * */
    public void setAvatarOnclickLinster(ImageView imageView,final EMGroup emGroup){
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity((new Intent(context, GroupDetailsActivity.class).putExtra("groupId", emGroup.getGroupId())));
            }
        });
    }
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.qunliao_common)
            .showImageForEmptyUri(R.drawable.qunliao_common) // resource or drawable
            .showImageOnFail(R.drawable.qunliao_common) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .cacheInMemory(false) // default
            .cacheOnDisk(true) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();
    /**
     * 获取未读消息的数量
     * */
    public int getUnReadMsg(){
        //获取未读通知的数量
        Map<String, User> user = AppContext.getInstance().getContactList();
        //添加消息数量
        if (user != null) {
            User user1 = user.get(Constant.NEW_FRIENDS_USERNAME);
            if (user1 != null) {
                int unRead = user1.getUnreadMsgCount();
                return unRead;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
 }